package com.sdvdxl.util;

import java.util.List;

import javax.servlet.ServletContext;

import com.sdvdxl.model.BlogTagEntity;
import com.sdvdxl.model.BlogTypeEntity;
import com.sdvdxl.service.BlogTagService;
import com.sdvdxl.service.BlogTypeService;

public class ApplicationData {
	private static ApplicationData appData;
	private ServletContext application;
	private BlogTypeService blogTypeService;
	private BlogTagService blogTagService;

	public BlogTypeService getBlogTypeService() {
		return blogTypeService;
	}

	public void setBlogTypeService(BlogTypeService blogTypeService) {
		this.blogTypeService = blogTypeService;
	}

	public BlogTagService getBlogTagService() {
		return blogTagService;
	}

	public void setBlogTagService(BlogTagService blogTagService) {
		this.blogTagService = blogTagService;
	}

	private static LoggerUtil logger = new LoggerUtil(ApplicationData.class);

	public ApplicationData() {
	}

	public ServletContext getContext() {
		return application;
	}

	public void setContext(ServletContext context) {
		this.application = context;
	}

	public static ApplicationData getInstance() {
		if (appData == null) {
			synchronized (ApplicationData.class) {
				if (appData == null) {
					appData = new ApplicationData();
				}
			}
		}

		return appData;
	}

	public void init() {
		ApplicationData.appData = this;
		logger.info("初始化常用数据：标签，分类");
		getBlogTags();
		getBlogTypes();
	}

	private void getBlogTags() {
		List<BlogTagEntity> blogTags = null;
		try {
			blogTags = blogTagService.getAll();
			application.setAttribute("blogTags", blogTags);
		} catch (Exception e) {
			logger.error(e);
		}
	}

	/**
	 * 获取所有博文分类并将其放置到application中
	 */
	private void getBlogTypes() {
		List<BlogTypeEntity> blogTypes = null;
		try {
			blogTypes = blogTypeService.getAll();
			application.setAttribute("blogTypes", blogTypes);
		} catch (Exception e) {
			logger.error(e);
		}
	}

	/**
	 * 更新博客类型数据
	 */
	public void updateBlogTypes() {
		logger.info("更新分类");
		getBlogTypes();
	}

	/**
	 * 更新博客标签数据
	 */
	public void updateBlogTags() {
		logger.info("更新标签");
		getBlogTags();
	}
}
